package com.penngo.gui.dfdiff.view;


import com.penngo.gui.dfdiff.utils.ImgUtil;
import com.penngo.gui.dfdiff.utils.LogUtils;

import javax.swing.*;
import javax.swing.plaf.basic.BasicButtonUI;
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Logger;

public class TabbedPaneClosable extends JTabbedPane {
    private Logger log = LogUtils.getLogger(TabbedPaneClosable.class);
    public TabbedPaneClosable(){

    }
    @Override
    public void addTab(String title, Component component) {
        super.addTab(title, component);
        setTabComponentAt(getTabCount() - 1, new ButtonTabComponent(title,this));
        setToolTipTextAt(getTabCount() - 1, title);
    }
    public void setTitleAt(int index, String title) {
        super.setTitleAt(index,title);
        setToolTipTextAt(index, title);
    }

    class ButtonTabComponent extends JPanel {
        private final JTabbedPane pane;
        public ButtonTabComponent(String title, JTabbedPane pane) {
            super(new FlowLayout(FlowLayout.LEFT, 0, 0));
            if (pane == null) {
                throw new NullPointerException("TabbedPane is null");
            }
            this.pane = pane;
            setOpaque(false);

            JLabel label = new JLabel() {
                private int len = 0;
                public String getText() {
                    int i = pane.indexOfTabComponent(ButtonTabComponent.this);
                    if (i != -1) {
                        FontMetrics fm = this.getFontMetrics(this.getFont());
                        String text  = pane.getTitleAt(i);
                        int lenTemp = getStringWidth(fm, text);
                        if(lenTemp != len){
                            len = lenTemp;
                            this.setSize(len, this.getHeight());
                        }
                        return text;
//                        return pane.getTitleAt(i);
                    }
                    return null;
                }
            };
            add(label);
            label.setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 5));

            JButton button = new TabButton();
            add(button);

            setBorder(BorderFactory.createEmptyBorder(4, 0, 0, 0));
        }
        /**
         * 字符串总宽度
         * @param str
         * @return
         */
        private int  getStringWidth(FontMetrics fm, String str) {
            char[]  strcha=str.toCharArray();
            int strWidth = fm.charsWidth(strcha, 0, str.length());
            return strWidth;
        }
        private class TabButton extends JButton implements ActionListener {
            private ImageIcon focusLostIcon;
            private ImageIcon focusGainedIcon;

            public TabButton() {
                int size = 17;
                this.setBackground(Color.BLACK);
                setPreferredSize(new Dimension(size, size));
//                setMinimumSize(new Dimension(size, size));
                setToolTipText("close this tab");
                focusLostIcon = ImgUtil.getIconAuto("/images/close-line.png", 17,17);
                focusGainedIcon = ImgUtil.getIconAuto("/images/close-circle-line.png", 17,17);
                setIcon(focusLostIcon);

                setUI(new BasicButtonUI());

                setContentAreaFilled(false);

                addMouseListener(new MouseAdapter() {
                    public void mouseEntered(MouseEvent e) {
                        Component component = e.getComponent();
                        if (component instanceof AbstractButton) {
                            AbstractButton button = (AbstractButton) component;
                            button.setIcon(focusGainedIcon);
                        }
                    }
                    public void mouseExited(MouseEvent e) {
                        Component component = e.getComponent();
                        if (component instanceof AbstractButton) {
                            AbstractButton button = (AbstractButton) component;
                            button.setIcon(focusLostIcon);
                        }
                    }
                });

                addActionListener(this);
            }

            public void actionPerformed(ActionEvent e) {
                int i = pane.indexOfTabComponent(ButtonTabComponent.this);
                if (i != -1) {
                    pane.remove(i);
                }
            }
        }
    }

    public static void main(String[] args) throws Exception {
        UIManager
                .setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        JFrame jframe = new JFrame();
        jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        int tabNumber = 5;
        TabbedPaneClosable pane = new TabbedPaneClosable();
        jframe.add(pane);
        pane.removeAll();
        for (int i = 0; i < tabNumber; i++) {
            String title = "Tab " + i;
            pane.add(title, new JLabel(title));
        }
//        pane.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT);
        jframe.setSize(new Dimension(400, 200));
        jframe.setLocationRelativeTo(null);
        jframe.setVisible(true);
    }

}
